const express = require('express')
const router = express.Router()
const humps = require('humps')
const db = require('../../database/db')

module.exports = (() => {
    // 订单管理
    router.get('/finances', async (req, res, next) => {
        try {
            let sql = ''
            req.query.from ? sql += 'AND r.`pick_car_time` >= "' + req.query.from + '" AND r.`pick_car_time` <= "' + req.query.to + '" ' : ''
            if (+req.query.depositToAchievement) {
                sql += 'AND r.`deposit_to_achievement` = 1 '
            } else {
                sql += 'AND r.`deposit_to_achievement` = 0 '
            }
            const doc = humps.camelizeKeys(await db.getFinances({ limit: req.query.limit, offset: req.query.offset, search: req.query.search, sql }))
            const { total } = await db.getFinancesTotal({ search: req.query.search, sql })
            const temp = []
            const promises = []
            doc.forEach(item => {
                const promise = new Promise(async resolve => {
                    const trial = item.trial ? await db.getTrialById(item.trial) : item.trial
                    item.isMortgage = item.isMortgage ? '按揭' : '全款'
                    item.trial = trial ? trial.name : '无'
                    temp.push(item)
                    resolve(temp)
                })
                promises.push(promise)
            })
            Promise.all(promises).then((data) => {
                res.send({
                    doc,
                    total
                })
            })
        } catch (err) {
            next(err)
        }
    })

    router.put('/editFinance/:id', async (req, res, next) => {
        try {
            let existFinance = await db.getFinanceById(req.params.id)
            if (!existFinance) {
                res.json({
                    status: 0,
                    msg: '该订单不存在！'
                })
                return
            }

            const data = {
                id: req.params.id,
                charge: req.body.charge,
                cost: req.body.cost,
                achievement: req.body.achievement
            }

            const existArchive = await db.getArchiveByPhone(req.body.phone)
            if (!existArchive) {
                const promotion = await db.getPromotionByName(req.body.promotion)
                const center = await db.getCenterByName(req.body.center)
                const dept = await db.getDeptByName({ name: req.body.dept, center: req.body.center })
                const salesman = await db.getSalesmanByName({ name: req.body.salesman, dept: req.body.dept, center: req.body.center })
                const distribution = await db.getDistributionByName(req.body.distribution)
                const trial = req.body.trial && await db.getTrialByName(req.body.trial)
                const warrantMan = req.body.warrantManId && await db.getWarrantManById(req.body.warrantManId)

                const archives = {
                    name: req.body.name,
                    loanAmount: req.body.loanAmount,
                    time: req.body.time,
                    warrantManId: warrantMan ? warrantMan.id : 0,
                    phone: req.body.phone,
                    promotion_id: promotion.id,
                    center_id: center.id,
                    department_id: dept.id,
                    salesman_id: salesman.id,
                    distribution_id: distribution.id,
                    loan_company_id: trial ? trial.id : 0,
                    cartype: req.body.cartype,
                }
                await db.addArchive(archives)
            }
            const success = await db.updateFinance(data) // 更新订单表数据

            if (success) {
                res.json({
                    status: 1,
                    msg: 'ok'
                })
            }
        } catch (err) {
            next(err)
        }
    })

    return router
})();